<?php 
namespace Util;

class SyncFile 
{
	const PATTERN_IMAGE='/<img\s.*?src=[\\]?[\'|\"]([^\"\']+)[\\]?[\'|\"]/';

	public static $base_dir='uploads';

	public static $save_dir='';

	public static $save_level=2;

	public static $erro=null;

	public static $default_ext='';

	public static function syncImg($save_dir,$filter,$is_file=false)
	{	
		self::$save_dir=$save_dir;
		self::$default_ext='jpg';

		return self::syncHtml($filter,self::PATTERN_IMAGE);
	}

	public static function syncFile($save_dir,$file,$default_ext='jpg')
	{	
		self::$save_dir=$save_dir;
		self::$default_ext=$default_ext;
		return self::saveFile($file);
	}

	public static function syncHtml($html_str,$pattern)
	{
		return preg_replace_callback($pattern,'self::replaceHtml',$html_str);
	}


	public static  function replaceHtml($matches)
	{
		$new_path=self::saveFile($matches[1]);

		return str_replace($matches[1],$new_path,$matches[0]);
	}



	public static function saveFile($file)
	{
		$save_path=self::getMd5Path($file);

		return @file_put_contents($save_path,file_get_contents($file))?'/'.$save_path:'';
	}



	public static function getMd5Path($file)
	{
		$ext=pathinfo($file, PATHINFO_EXTENSION);

		$ext=$ext?$ext:(self::$default_ext);

		$md5=md5($file);

		$md5_array=str_split(md5($file,false),3);

		for($i=0;$i<self::$save_level;$i++) {
			$md5_path.=$md5_array[$i].'/';
		}

		$path=self::$base_dir.'/'.self::$save_dir.'/'.$md5_path;

		self::mkDirs($path);

		return $path.$md5.'.'.$ext;

	}


	public static  function mkDirs($dir){

	    if(!is_dir($dir)){
	        if(!self::mkDirs(dirname($dir))){
	            return false;
	        }
	        if(!mkdir($dir,0777)){
	            return false;
	        }
	    }
	    return true;
	}
}


?>